package czy.demo.view;

import czy.demo.pojo.User;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/* 构建XLS视图，xls为excel2003及之前版本文件 */
public class XLSView extends AbstractXlsView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<User> users = (List<User>) model.get("users");

        Sheet sheet = workbook.createSheet("基本信息");

        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);

        sheet.setHorizontallyCenter(true);
        sheet.setVerticallyCenter(true);

        Row header = sheet.createRow(0);
        header.setRowStyle(style);
        header.createCell(0).setCellValue("序号");
        header.createCell(1).setCellValue("名字");
        header.createCell(2).setCellValue("邮箱");
        int rowNumber = 1;
        for (User user :users) {
            Row row = sheet.createRow(rowNumber++);
            row.setRowStyle(style);
            row.createCell(0).setCellValue(users.indexOf(user)+1);
            row.createCell(1).setCellValue(user.getName());
            row.createCell(2).setCellValue(user.getAge());
        }
    }
}
